package com.smcdd.cdb.dbo.cdb_dbo.network.factory;

import com.smcdd.cdb.dbo.cdb_dbo.network.AuthInterceptor;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpConstants;
import com.smcdd.cdb.dbo.cdb_dbo.network.ResponseInterceptor;
import com.smcdd.cdb.dbo.cdb_dbo.network.RetrofitService;
import com.smcdd.cdb.dbo.cdb_dbo.network.error_exception.MyGsonConverterFactory;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by Jeremylee on 2017/6/5.
 */

public class RetrofitFactory {

    private static volatile RetrofitFactory mInstanse = null;

    public RetrofitService mApi;

    public RetrofitFactory() {
        mApi = provideHotApi();

    }


    public static RetrofitFactory getmInstanse() {
        if(mInstanse==null){
            synchronized (RetrofitFactory.class){
                if(mInstanse==null){
                    mInstanse = new RetrofitFactory();
                }
            }
        }
        return mInstanse;
    }


    private RetrofitService provideHotApi() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpConstants.BaseURL_DEV)
                .client(provideOKHttpClient())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(new ApiErrorAwareConverterFactory(
                        new EmptyJsonLenientConverterFactory(MyGsonConverterFactory.create())))
                .build();

        return retrofit.create(RetrofitService.class);
    }

    private OkHttpClient provideOKHttpClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(HttpConstants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .connectTimeout(HttpConstants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(new AuthInterceptor())
                .addInterceptor(new ResponseInterceptor())
                .build();


        return okHttpClient;
    }
}
